/*
 * @Author: Jone XIn
 * @Date: 2022-01-10 21:18:20
 * @LastEditTime: 2022-01-10 23:07:25
 * @Description: 监听文件改变类
 */
const fs = require('fs');
const md5 = require('md5');
const path = require('path');
const { deviceSeq, Device } = require('../model/device');
const { uploadNewsFileBuffer } = require('../http/axios');

class WatchFile {
    preveMd5 = null; //
    fsWait = false;  // 延时时间
    watchPath = []; // 项目路径数组

    constructor(params) {
        this.init();
    }

    init() { }
    /**
     * 增加路径
     * @param {Object} deviceInfo
     */
    async addpath(deviceInfo) {
        try {
            // 插入信息
            await Device.addDeviceInfo(deviceInfo);
            // 将整个文件先同步到服务端
            // 获取path
            return this.startWatchFile(deviceInfo.watch_path);
        } catch (_) {
            console.log(_);
            return _;
        }
    }

    /**
     * 监控项目
     * @param {String} filePath 项目路径
     * @returns Boolen
     */
    startWatchFile(filePath) {
        // 观察文件的原路径
        try {
            fs.watch(filePath, (event, filename) => {
                if (filename) {
                    if (this.fsWait) return;
                    this.fsWait = setTimeout(() => {
                        this.fsWait = false;
                    }, 100)
                    let currentMd5 = md5(fs.readFileSync(filePath + '/' + filename))
                    if (currentMd5 == this.preveMd5) {
                        console.log('文件无更新');
                        return false;
                    }
                    this.preveMd5 = currentMd5
                    console.log(`${filePath}文件发生更新`);

                    // 发送更新的文件到服务器上（buffer)
                    const fileBuffer = fn.readFileSync(fs.readFileSync(filePath + '/' + filename));
                    let res = uploadNewsFileBuffer(fileBuffer);
                    if (res.code == 200) console.log(`【${filename}】上传成功!`);
                }
            })
            return true;
        } catch (_) {
            console.log(_);
            return _;
        }
    }
}

module.exports = WatchFile;
